package com.gzhryc.shared_device.iot.code.services;

import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.iot.code.dao.IOTLogsRecordDao;
import com.gzhryc.shared_device.iot.code.dao.db.IOTLogsRecord;
import com.gzhryc.shared_device.iot.code.services.dto.IOTLogsRecordSearch;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class IOTLogsRecordService {

    static Logger log = Logger.getLogger(IOTLogsRecordService.class);

    public static IOTLogsRecordService self() {
        return MultiDBTools.getService(IOTLogsRecordService.class, true);
    }

    public static IOTLogsRecordService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, IOTLogsRecordService.class, true);
    }

    IOTLogsRecordDao dao;

    public IOTLogsRecordService(String jdbcKey) {
        dao = new IOTLogsRecordDao(jdbcKey);
    }

    public List<IOTLogsRecord> findBySearch(IOTLogsRecordSearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().ge("createDate",search.getStartDate());
        conditions.and().le("createDate",search.getEndDate());
        conditions.desc("createDate");
        try {
            return dao.findByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countBySearch(IOTLogsRecordSearch search){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().ge("createDate",search.getStartDate());
        conditions.and().le("createDate",search.getEndDate());
        try {
            return dao.count(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public boolean add(IOTLogsRecord logsRecord){
        logsRecord.setCreateDate(new Date());
        try {
            return dao.insert(logsRecord) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }
}
